package com.wenhuitec.android.tang.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.dhkj.web.bean.AddrTree;
import com.dhkj.web.bean.Bmzl;
import com.dhkj.web.bean.ProductModel;
import com.dhkj.web.bean.Zweekmenubak;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.wenhuitec.android.tang.R;
import com.wenhuitec.android.tang.config.SystemInit;
import com.wenhuitec.android.tang.config.SystemParam;
import com.wenhuitec.android.tang.eventb.FoodsClickEvent;
import com.wenhuitec.android.tang.sysui.model.CarFoodsModel;
import com.wenhuitec.android.tang.sysui.model.PickModel;
import com.wenhuitec.android.tang.sysui.view.PickView;
import com.wenhuitec.android.tang.ui.adapter.CarFoodsAdapter;
import com.wenhuitec.android.tang.ui.adapter.MainFoodsAdapter;
import com.wenhuitec.android.tang.ui.adapter.SelectFoodsAdapter;
import com.wenhuitec.android.tang.ui.adapter.ShaiXuanAdapter;
import com.wenhuitec.android.tang.ui.dialog.MsgDialog;
import com.wenhuitec.android.tang.ui.dialog.PaySelectDepotDialog;
import com.wenhuitec.android.tang.ui.dialog.PaySelectDialog;
import com.wenhuitec.android.tang.ui.view.MyGridSpacingItemDecoration;
import com.wenhuitec.android.tang.util.BytesUtil;
import com.wenhuitec.android.tang.util.PrintUtil;
import com.wenhuitec.android.tang.util.ScanKeyManager;
import com.wenhuitec.android.tang.util.UsbPrinter;
import com.wsm.hidlib.HIDManager;
import com.wsm.hidlib.callback.HIDDataListener;
import com.wsm.hidlib.callback.HIDOpenListener;
import com.wsm.hidlib.callback.HIDSequenceNumberListener;
import com.wsm.hidlib.constant.ConnectCostant;
import com.wsm.hidlib.constant.FormatConstant;
import com.wsm.hidlib.util.HexUtil;
import com.wsm.hidlib.util.StringFormat;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ActivityCK extends AppCompatActivity {

    private static String TAG = "ActivityCK";
    private Context mContext;
    private GridView mGridView;
    private RecyclerView foodsRv;
    private RecyclerView recyclerView;

    private TextView amountCountTv;
    private TextView amountPriceTv;

    private TextView posNameTv;

    private List<AddrTree> addrTreeList;
    private Map<Integer, List<Bmzl>> mBmzlMap;
    private Map<Integer, List<Zweekmenubak>> zWeekMenuBakMap;

    private String addr;
    private String bmzl;
    private CarFoodsAdapter carFoodsAdapter;
    private SelectFoodsAdapter selectFoodsAdapter;
    private Button clearBut;

    private Button saixuanBut;

    MainFoodsAdapter mainFoodsAdapter;
    private HIDSequenceNumberListener mHidSequenceNumberListener;

    private List<ProductModel> productModelList;
    private UsbPrinter usbPrinter;
    private String foramt = FormatConstant.FORMAT_UTF8;
    private int READ_OK = 1;
    private StringBuffer stringBuffer;
    private PopupWindow popupWindow;

    private ShaiXuanAdapter shaiXuanAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_ck);
        mContext = this;
        stringBuffer = new StringBuffer();
        addrTreeList = SystemInit.getInstance(mContext).getAddrTreeList();
        mBmzlMap = SystemInit.getInstance(mContext).getBmzlList();
        zWeekMenuBakMap = SystemInit.getInstance(mContext).getzWeekMenuBakMap();
        EventBus.getDefault().register(this);
        foodsRv = findViewById(R.id.foodsGv);
        amountCountTv = findViewById(R.id.amountCountTv);
        amountPriceTv = findViewById(R.id.amountPriceTv);
        clearBut = findViewById(R.id.clearBut);
        posNameTv = findViewById(R.id.posNameTv);
        recyclerView = findViewById(R.id.carFoodsRv);
        saixuanBut = findViewById(R.id.saixuanBut);
        selectFoodsAdapter = new SelectFoodsAdapter(this);
        SharedPreferences sharedPreferences = getSharedPreferences("systemI", Context.MODE_PRIVATE); //私有数据

        initDevicePos();

        findViewById(R.id.toPayBut).setOnClickListener(v -> {
            Intent intent = new Intent(mContext, PaySelectDepotDialog.class);
            List<CarFoodsModel> carFoodsModels = carFoodsAdapter.getList();
            intent.putExtra("data", JSONArray.toJSONString(carFoodsModels));
            startActivityForResult(intent, 1011);
        });
        findViewById(R.id.qiehuanBut).setOnClickListener(view -> {
            MsgDialog msgDialog = new MsgDialog();
            msgDialog.show(mContext, "切换将会清空并重新加载商品，是否继续", new MsgDialog.OnBottomClickListener() {
                @Override
                public void positive() {
                    carFoodsAdapter.clearCar();
                    String userId = sharedPreferences.getString("user", "");
                    String xiaoMaiBuPos = sharedPreferences.getString("xiaoMaiBuPos", "");
                    String ziXiaoPos = sharedPreferences.getString("ziXiaoPos", "");
                    SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                    if (userId.equals(xiaoMaiBuPos)) {
                        editor.putString("user", ziXiaoPos);
                    } else if (userId.equals(ziXiaoPos)) {
                        editor.putString("user", xiaoMaiBuPos);
                    }
                    editor.commit();
                    initFoods();
                    initDevicePos();
                }

                @Override
                public void negative() {

                }

            });
        });
        carFoodsAdapter = new CarFoodsAdapter(mContext);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(carFoodsAdapter);
        carFoodsAdapter.setCarFoodsAmountListener((amountPrice, amountCount) -> {
            amountCountTv.setText("x" + amountCount.stripTrailingZeros().toPlainString() + " 份");
            amountPriceTv.setText("￥" + amountPrice.stripTrailingZeros().toPlainString() + "  元");
        });
        clearBut.setOnClickListener(v -> {
            MsgDialog msgDialog = new MsgDialog();
            msgDialog.show(mContext, "是否清空", new MsgDialog.OnBottomClickListener() {
                @Override
                public void positive() {
                    carFoodsAdapter.clearCar();
                }

                @Override
                public void negative() {

                }

            });
        });
        mainFoodsAdapter = new MainFoodsAdapter(mContext);
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(mContext);
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        foodsRv.setLayoutManager(layoutManager3);
        foodsRv.setAdapter(mainFoodsAdapter);

        findViewById(R.id.readCardBut).setOnClickListener(view -> {
            ReadCardActivity.startAct(mContext);
        });

        saixuanBut.setOnClickListener(view -> {
            int[] location = new int[2];
            saixuanBut.getLocationOnScreen(location);
            saixuanBut.getLocationInWindow(location);
            System.out.println("屏幕内坐标:" + location[0] + "," + location[1]);
            System.out.println("在父坐标:" + saixuanBut.getLeft() + "," + saixuanBut.getTop());
            popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0], (location[1] + saixuanBut.getHeight()));

        });
        initPopupWindow();
    }

    //    /*创建PopupWindow*/
    protected void initPopupWindow() {
        final View popipWindow_view = getLayoutInflater().inflate(R.layout.item_saixuan, null, false);
        popupWindow = new PopupWindow(popipWindow_view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//        popupWindow.setAnimationStyle(R.style.AnimationTopFade);

        popipWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popipWindow_view != null && popipWindow_view.isShown()) {
                    popupWindow.dismiss();
                }
                return false;
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));

        shaiXuanAdapter = new ShaiXuanAdapter(mContext);
        RecyclerView saixuanRv = popipWindow_view.findViewById(R.id.saixuanRv);
        GridLayoutManager productLayoutManager = new GridLayoutManager(mContext, 3);
        productLayoutManager.setOrientation(RecyclerView.VERTICAL);
        saixuanRv.setLayoutManager(productLayoutManager);
        saixuanRv.setAdapter(shaiXuanAdapter);
        saixuanRv.addItemDecoration(new MyGridSpacingItemDecoration(3));
        shaiXuanAdapter.setUserClick(productModel -> {
            if (productModel == null) {
                mainFoodsAdapter.setDatas(productModelList);
            } else {
                ProductModel productModel2 = productModelList.stream().filter(productModel1 -> productModel1.getClsid().equals(productModel.getClsid()))
                        .findFirst().orElse(null);
                if (productModel2 != null) {
                    List<ProductModel> productModelList1 = new ArrayList<>();
                    productModelList1.add(productModel2);
                    mainFoodsAdapter.setDatas(productModelList1);
                }
            }
            popupWindow.dismiss();

        });


    }

    private void initDevicePos() {
        SharedPreferences sharedPreferences = getSharedPreferences("systemI", Context.MODE_PRIVATE); //私有数据
        String userId = sharedPreferences.getString("user", "");
        String xiaoMaiBuPos = sharedPreferences.getString("xiaoMaiBuPos", "");
        String ziXiaoPos = sharedPreferences.getString("ziXiaoPos", "");
        posNameTv.setText("当前机号：" + userId);
        if (userId.equals(xiaoMaiBuPos)) {
            posNameTv.setText(posNameTv.getText() + "(小卖部)");
        } else if (userId.equals(ziXiaoPos)) {
            posNameTv.setText(posNameTv.getText() + "(自销)");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FoodsClickEvent event) {
        //分发所有eventbus事件到副屏
        carFoodsAdapter.addFoods(event.getDevice());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1011 && resultCode == RESULT_OK) {
            carFoodsAdapter.clearCar();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private HIDOpenListener mHIDOpenListener;
    private HIDDataListener mHidDataListener;

    private void initHID() {
        HIDManager.getInstance().enableLog(true);
        HIDManager.getInstance().openHID(mContext, mHIDOpenListener, mHidDataListener);

    }

    private void initListener() {
        //回调数据有关页面展示的请在主线程进行。
        mHIDOpenListener = new HIDOpenListener() {
            @Override
            public void openSuccess(final int openSuccessStatus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (openSuccessStatus == ConnectCostant.USB_CONNECT) {
                            System.out.println("连接USB");

                        } else if (openSuccessStatus == ConnectCostant.COMMUNICATION_OPEN) {
                            System.out.println("通讯建立");
                        }
                    }
                });

            }

            @Override
            public void openError(int openErrorStatus) {
                if (openErrorStatus == ConnectCostant.USB_DISCONNECT) {
                    //USB断开
                    System.out.println("断开USB");
                }
                if (openErrorStatus == ConnectCostant.COMMUNICATION_CLOSE) {
                    //服务销毁
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("通讯断开");
                        }
                    });

                }
            }

        };

        mHidDataListener = new HIDDataListener() {
            @Override
            public void onDataReceived(byte status, String dataMessage) {
                if (!TextUtils.isEmpty(dataMessage)) {
                    String result = dataMessage;
                    System.out.println("onDataReceived: length:" + dataMessage.length() + "   content:" + result);
                    Message message = Message.obtain();
                    message.what = READ_OK;
                    message.obj = result;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onOriginalDataReceived(byte status, byte[] bytes, int length) {
                String formatHexString = HexUtil.formatHexString(bytes);
                System.out.println("onOriginalDataReceived: " + formatHexString);
            }
        };
        mHidSequenceNumberListener = new HIDSequenceNumberListener() {
            @Override
            public void onSequenceNumberReceived(byte[] bytes, int length) {

                if (length > 0) {
                    String formatChar = StringFormat.bytes2String(bytes, foramt);
                    System.out.println("onSequenceNumberReceived: " + formatChar);
                    Message message = Message.obtain();
                    message.what = READ_OK;
                    message.obj = formatChar;
                    handler.sendMessage(message);
                }
            }
        };

    }

    private void initFoods() {
        SharedPreferences sharedPreferences =
                mContext.getSharedPreferences("systemI", Context.MODE_PRIVATE); //私有数据
        String user = sharedPreferences.getString("user", "");
        RequestUtils.getProduct(mContext, user, new MyObserverRes<List<ProductModel>>(mContext) {
            @Override
            public void onSuccess(List<ProductModel> result) {
                mainFoodsAdapter.setDatas(result);
                shaiXuanAdapter.setDatas(result);
                productModelList = result;
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initFoods();
        if (usbPrinter == null) {
            usbPrinter = UsbPrinter.getInstance(this);
        }

        initListener();
        initHID();
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == READ_OK) {
                String data = (String) msg.obj;
                System.out.println(data);
                ProductModel.Device device = null;
                for (ProductModel goo : productModelList) {
                    ProductModel.Device deviceTemp = goo.getDeviceList().stream()
                            .filter(device1 -> data.trim().equals(device1.getDeviceID_YWM().trim())).findFirst().orElse(null);
                    if (deviceTemp != null) {
                        device = deviceTemp;
                        FoodsClickEvent foodsClickEvent = new FoodsClickEvent();
                        foodsClickEvent.setDevice(device);
                        EventBus.getDefault().post(foodsClickEvent);
                        break;
                    }
                }
                if (device == null) {
                    Toast.makeText(mContext, "查找不到该商品", Toast.LENGTH_LONG).show();
                }

            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
//        if (usbPrinter != null) {
//            usbPrinter.close();
//            usbPrinter = null;
//        }

        HIDManager.getInstance().closeHID();
    }
}